<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <h1>库存管理</h1>
                <div class="common-layout topsize">
                    <el-container>
                        <el-aside width="650px">
                            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                                <el-form-item style="width:200px;">
                                    <el-input v-model="formInline.pname" placeholder="药品名称" />
                                </el-form-item>
                                <el-form-item style="width:100px;">
                                    <el-input v-model="formInline.startPrice" placeholder="最低价" />
                                </el-form-item>
                                <el-form-item style="width:100px;">
                                    <el-input v-model="formInline.endPrice" placeholder="最高价" />
                                </el-form-item>
                                <el-form-item style="width:200px;">
                                    <el-select v-model="formInline.ptype" class="m-2" placeholder="药品类别">
                                        <el-option v-for="item in typeList" :key="item.tid" :label="item.type"
                                            :value="item.type" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item style="width:80px;">
                                    <el-button type="primary" @click="getData()">查询</el-button>
                                </el-form-item>
                                <el-form-item style="width:80px; margin-left: 10px;">
                                    <el-button type="primary" @click="reset">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </el-aside>
                        <el-drawer v-model="drawer" title="添加药品" :direction="direction" :before-close="handleClose">
                            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                                <el-form-item label="药品名称">
                                    <el-input v-model="formInline.pname" placeholder="药品名称" />
                                </el-form-item>
                                <el-form-item label="药品单价">
                                    <el-input v-model="formInline.pprice" placeholder="药品单价" />
                                </el-form-item>
                                <el-form-item label="药品数量">
                                    <el-input v-model="formInline.pcount" placeholder="药品数量" />
                                </el-form-item>
                                <el-form-item label="药品描述">
                                    <el-input v-model="formInline.pdes" placeholder="药品描述" />
                                </el-form-item>
                                <el-form-item label="药品类别">
                                    <el-select v-model="formInline.ptype" class="m-2" placeholder="药品类别">
                                        <el-option v-for="item in typeList" :key="item.tid" :label="item.type"
                                            :value="item.type" />
                                    </el-select>
                                </el-form-item>
                            </el-form>
                            <template #footer>
                                <div style="flex: auto">
                                    <el-button @click="cancelClick">取消</el-button>
                                    <el-button type="primary" @click="confirmClick">提交</el-button>
                                </div>
                            </template>
                        </el-drawer>
                        <el-drawer v-model="drawer3" title="更新药品" :direction="direction" :before-close="handleClose">
                            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                                <el-form-item label="药品名称">
                                    <el-input v-model="formInline.pname" placeholder="药品名称" />
                                </el-form-item>
                                <el-form-item label="药品单价">
                                    <el-input v-model="formInline.pprice" placeholder="药品单价" />
                                </el-form-item>
                                <el-form-item label="药品数量">
                                    <el-input v-model="formInline.pcount" placeholder="药品数量" />
                                </el-form-item>
                                <el-form-item label="药品描述">
                                    <el-input v-model="formInline.pdes" placeholder="药品描述" />
                                </el-form-item>
                                <el-form-item label="药品类别">
                                    <el-select v-model="formInline.ptype" class="m-2" placeholder="药品类别">
                                        <el-option v-for="item in typeList" :key="item.tid" :label="item.type"
                                            :value="item.type" />
                                    </el-select>
                                </el-form-item>
                            </el-form>
                            <template #footer>
                                <div style="flex: auto">
                                    <el-button @click="cancelClick">取消</el-button>
                                    <el-button type="primary" @click="confirmClick3">提交</el-button>
                                </div>
                            </template>
                        </el-drawer>
                        <el-drawer v-model="drawer2" title="批量添加药品" :direction="direction" :before-close="handleClose">
                            <a :href="excelTemplateUrl" download>下载Excel模板</a>
                            <el-upload drag :limit=limitNum :auto-upload="false" accept=".xlsx" :action="UploadUrl()"
                                :before-upload="beforeUploadFile" :on-change="fileChange" :on-exceed="exceedFile"
                                :on-success="handleSuccess" :on-error="handleError" :file-list="fileList">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
                            </el-upload>
                            <template #footer>
                                <div style="flex: auto">
                                    <el-button @click="cancelClick">取消</el-button>
                                    <el-button type="primary" @click="confirmClickExcel">提交</el-button>
                                </div>
                            </template>
                        </el-drawer>
                    </el-container>
                </div>
            </el-header>
            <el-main>
                <div class="common-layout">
                    <el-container style="display: block; ">
                        <el-table :data="dataList" style="width: 100%" empty-text="暂无数据"
                            :header-cell-style="{ background: '#EFF0FD', color: '#606266' ,width:'100%'}"
                            :key="Math.random()" border>
                            <el-table-column fixed prop="pno" label="药品ID" show-overflow-tooltip />
                            <el-table-column prop="pname" label="药品名称" show-overflow-tooltip />
                            <el-table-column prop="pprice" label="药品单价" show-overflow-tooltip />
                            <el-table-column prop="pcount" label="药品数量" show-overflow-tooltip />
                            <el-table-column prop="pdes" label="药品描述" show-overflow-tooltip />
                            <el-table-column prop="ptype" label="药品类别" show-overflow-tooltip />
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <el-button @click="handleUpdate(scope.$index, scope.row)" type="primary">修改</el-button>
                                    <el-button type="primary"
                                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="bar">
                            <span>总计 <span class="number">{{ formInline.count }}</span> 条数据</span>
                            <el-pagination :page-size="formInline.pageSize"
                                v-model:current-page="formInline.currentPage" layout="prev, pager, next"
                                :total="formInline.count" @current-change="getData()" />
                        </div>
                    </el-container>
                </div>
            </el-main>
        </el-container>
    </div>


</template>

<script>
    import { ElMessage } from 'element-plus'
    import { ElMessageBox } from 'element-plus'
    export default {
        name: 'VueWithdrawal',

        data() {
            return {
                formInline: {
                    pname: '',
                    startPrice: '',
                    endPrice: '',
                    ptype: '',
                    pcount: '',
                    pprice: '',
                    pdes: '',
                    currentPage: 1, // 第几页
                    pageSize: 9, // 每页多少条
                    count: '', // 总记录数
                    pid: ''
                },
                dataList: [],
                typeList: [],
                drawer: false,
                direction: "rtl",
                drawer2: false,
                limitNum: 1,  // 上传excell时，同时允许上传的最大数
                fileList: [],// excel文件列表
                excelTemplate: "添加药品Excel模板.xlsx", // Excel 模板文件名
                drawer3: false,
            };
        },

        mounted() {
            this.getData();
            this.getType();
        },
        computed: {
            excelTemplateUrl() {
                return `${process.env.BASE_URL}${this.excelTemplate}`; // Excel 模板完整 URL
            },
        },

        methods: {
            reset() {
                this.formInline.pname = '',
                    this.formInline.startPrice = '',
                    this.formInline.endPrice = '',
                    this.formInline.ptype = '',
                    this.getData();
            },
            // 药品类别
            async getType() {
                var that = this;
                that.$http.get('type/getType')
                    .then(function (result) {
                        if (result) {
                            that.typeList = result.data;
                        }
                    })
                    .catch(function (error) {
                        console.log("药品类别错误信息", error);
                    })
            },
            // 药品信息
            async getData() {
                var that = this;
                let pno = 1;
                this.$http.get("product/allProductInfo", {
                    params: {
                        pname: that.formInline.pname,
                        startPrice: that.formInline.startPrice,
                        endPrice: that.formInline.endPrice,
                        ptype: that.formInline.ptype,
                        current: that.formInline.currentPage,
                        size: that.formInline.pageSize
                    }
                })
                    .then(function (result) {
                        if (result) {
                            that.dataList = result.records.map((item) => {
                                item = {
                                    ...item,
                                    pno: pno
                                }
                                pno++;
                                return item;
                            })
                            //总数
                            that.formInline.count = result.total;
                        } else {
                            ElMessage({
                                message: "药品信息查询失败",
                                type: 'error',
                            })
                        }
                    })
                    .catch(function (error) {
                        ElMessage({
                            message: "服务器内部错误",
                            type: 'error',
                        })
                        console.log("药品信息错误信息", error);
                    })
            },
            // 分页组件
            handlePageChange(currentPage) {
                this.formInline.currentPage = currentPage
                this.getData();
            },
            handleSizeChange(pageSize) {
                this.formInline.pageSize = pageSize
                this.getData();
            },
            // 单个删除
            handleDelete(index, row) {
                var that = this;
                ElMessageBox.confirm(
                    '是否删除? （请谨慎考虑！）',
                    'Warning',
                    {
                        confirmButtonText: '删除',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        this.$http.get('product/' + row.pid)
                            .then(function (result) {
                                that.getData();
                            })
                            .catch(function (error) {
                                console.log("删除错误信息：", error);
                            })
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消删除',
                        })
                    })

            },
            // 单个添加弹层
            addOneProduct(index, row) {
                this.drawer = true;
            },
            // 批量添加弹层
            addExcelProduct() {
                this.drawer2 = true;
            },
            // 更新药品
            handleUpdate(index, row) {
                this.drawer3 = true;
                this.formInline.pname = row.pname;
                this.formInline.pprice = row.pprice;
                this.formInline.pdes = row.pdes;
                this.formInline.pcount = row.pcount;
                this.formInline.ptype = row.ptype;
                this.formInline.pid = row.pid;
            },
            // 单个添加药品
            handleClose() {
                ElMessageBox.confirm('确定取消添加药品吗?')
                    .then(() => {
                        this.drawer = false;
                        this.drawer2 = false;
                        this.drawer3 = false;
                        this.formatone();
                    })
            },
            formatone() {
                this.formInline.pname = "";
                this.formInline.pprice = "";
                this.formInline.pcount = "";
                this.formInline.pdes = "";
                this.formInline.ptype = "";
                this.formInline.pid = "";
            },
            cancelClick() {
                this.drawer = false;
                this.drawer2 = false;
                this.drawer3 = false;
            },
            confirmClick() {
                ElMessageBox.confirm("确定添加药品吗？")
                    .then(() => {
                        let that = this;
                        that.$http.post("product/addproduct", that.formInline)
                            .then(function (result) {
                                that.formatone();
                            })
                            .catch(function (error) {

                            })
                        that.drawer = false;
                    })
                    .catch(() => {

                    })
            },
            confirmClick3() {
                ElMessageBox.confirm("确定修改药品吗？")
                    .then(() => {
                        let that = this;
                        that.$http.post("product/updateproduct", that.formInline)
                            .then(function (result) {
                                that.formatone();
                                that.getData();
                                that.drawer3 = false;
                            })
                            .catch(function (error) {

                            })

                    })
                    .catch(() => {

                    })
            },
            /* ------------------- excel ------------------- */
            // 文件超出个数限制时的钩子
            exceedFile(files, fileList) {
                this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
            },
            // 文件状态改变时的钩子
            fileChange(file, fileList) {
                this.fileList.push(file.raw);
            },
            // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
            beforeUploadFile(file) {
                let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
                let size = file.size / 1024 / 1024;
                if (extension !== 'xlsx') {
                    this.$message.warning('只能上传后缀是.xlsx的文件');
                }
                if (size > 10) {
                    this.$message.warning('文件大小不得超过10M');
                }
            },
            // 文件上传成功时的钩子
            handleSuccess(res, file, fileList) {
                this.$message.success('文件上传成功');
            },
            // 文件上传失败时的钩子
            handleError(err, file, fileList) {
                this.$message.error('文件上传失败');
            },
            UploadUrl: function () {
                // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
                return ""
            },
            // 批量添加
            confirmClickExcel() {
                var that = this;
                if (that.fileList.length === 0) {
                    that.$message.warning('请上传文件');
                } else {
                    let form = new FormData();
                    for (let i = 0; i < that.fileList.length; i++) {
                        form.append('file', that.fileList[i]);
                    }
                    that.$http({
                        method: "post",
                        url: "/product/excelImport",
                        headers: {
                            'Content-type': 'multipart/form-data'
                        },
                        data: form
                    })
                        .then(function (result) {
                            that.getData();
                            that.drawer2 = false;
                        })
                        .catch(function (error) {
                            console.log(error, "excel错误信息");
                        })
                }
            },


        },
    };
</script>

<style lang="css" scoped>
    .topsize {
        margin-top: 10px;
    }

    h1 {
        font-size: 30px;
        font-weight: 600;
        font-family: "微软雅黑";
        color: rgb(73, 72, 72);
    }

    .el-aside {
        width: 100%;
    }

    .bar {
        border-top: 1px solid silver;
        line-height: 56px;
    }

    .number {
        color: red;
    }

    .el-main {
        padding: 0 !important;
        overflow: hidden;
        margin-top: 30px;
    }

    .el-header {
        height: 50px;
        padding-left: 0;
    }


    .el-aside {
        overflow: hidden;
    }

    .el-form-item {
        margin-right: 10px;
    }

    .flex {
        margin-top: 20px;
    }

    /* 下方数据 */
    .bottom-header {
        height: 370px;
    }

    .el-table {
        margin-top: 20px;
        box-shadow: 0 0 5px rgb(195, 206, 217);
    }

    .bottom-bar {
        border-top: 1px solid silver;
    }

    .el-pagination {
        float: left;
        margin-top: 10px;
    }

    .bottom-bar>span {
        margin-top: 16px;
        display: inline-block;

    }
</style>